"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { CalendarIcon, FilterIcon, SearchIcon, SlidersIcon, TrashIcon } from "lucide-react"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"
import { useHistory } from "@/components/history-context"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"

export function HistoryGallery() {
  const { history, clearHistory } = useHistory()
  const [loading, setLoading] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")

  const filteredHistory = history.filter((item) => {
    if (!searchQuery) return true

    // 在对象名称中搜索
    const hasMatchingObject = item.objects.some((obj) => obj.name.toLowerCase().includes(searchQuery.toLowerCase()))

    return hasMatchingObject
  })

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-col gap-4 sm:flex-row">
        <div className="relative flex-1">
          <SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            type="search"
            placeholder="搜索检测结果..."
            className="pl-8"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="icon">
            <FilterIcon className="h-4 w-4" />
            <span className="sr-only">筛选</span>
          </Button>
          <Button variant="outline" size="icon">
            <SlidersIcon className="h-4 w-4" />
            <span className="sr-only">排序</span>
          </Button>
          <Button variant="outline" size="icon">
            <CalendarIcon className="h-4 w-4" />
            <span className="sr-only">日期</span>
          </Button>
          <AlertDialog>
            <AlertDialogTrigger asChild>
              <Button variant="outline" size="icon" className="text-red-500 hover:bg-red-50">
                <TrashIcon className="h-4 w-4" />
                <span className="sr-only">清空历史</span>
              </Button>
            </AlertDialogTrigger>
            <AlertDialogContent>
              <AlertDialogHeader>
                <AlertDialogTitle>确认清空历史记录</AlertDialogTitle>
                <AlertDialogDescription>
                  此操作将删除所有历史检测记录，且无法恢复。确定要继续吗？
                </AlertDialogDescription>
              </AlertDialogHeader>
              <AlertDialogFooter>
                <AlertDialogCancel>取消</AlertDialogCancel>
                <AlertDialogAction onClick={clearHistory} className="bg-red-500 hover:bg-red-600">
                  确认清空
                </AlertDialogAction>
              </AlertDialogFooter>
            </AlertDialogContent>
          </AlertDialog>
        </div>
      </div>

      {loading ? (
        <div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
          {Array(8)
            .fill(0)
            .map((_, i) => (
              <Card key={i} className="overflow-hidden">
                <Skeleton className="aspect-square" />
                <CardFooter className="p-4">
                  <Skeleton className="h-4 w-full" />
                </CardFooter>
              </Card>
            ))}
        </div>
      ) : filteredHistory.length === 0 ? (
        <div className="flex flex-col items-center justify-center rounded-lg border border-dashed p-8 text-center">
          <p className="text-lg font-medium">未找到结果</p>
          <p className="text-muted-foreground">{searchQuery ? "没有匹配的检测结果" : "您还没有上传过照片"}</p>
          {searchQuery ? (
            <Button variant="outline" className="mt-4" onClick={() => setSearchQuery("")}>
              清除搜索
            </Button>
          ) : (
            <Button asChild className="mt-4">
              <Link href="/dashboard">上传照片</Link>
            </Button>
          )}
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
          {filteredHistory.map((item, index) => {
            // 为前三个图片设置特定的 URL 和标签
            let imageUrl = item.imageUrl
            let tags = item.objects.slice(0, 3).map((obj) => obj.name)
            let objectsCount = item.objects.length

            if (index === 0) {
              imageUrl = "/03.png"
              tags = ["狗", "草坪", "花", "宠物"]
              objectsCount = tags.length
            } else if (index === 1) {
              imageUrl = "/02.png"
              tags = ["水", "瓶子", "物品", "室内"]
              objectsCount = tags.length
            } else if (index === 2) {
              imageUrl = "/04.png"
              tags = ["树", "绿色", "人", "天空"]
              objectsCount = tags.length
            }

            return (
              <Link key={item.id} href={`/dashboard/results/${item.id}`}>
                <Card className="overflow-hidden transition-all hover:shadow-md">
                  <div className="relative aspect-square">
                    <Image
                      src={imageUrl || "/placeholder.svg"}
                      alt={`检测结果 ${item.id}`}
                      fill
                      className="object-cover"
                      unoptimized
                    />
                  </div>
                  <CardContent className="p-3">
                    <div className="flex flex-wrap gap-1">
                      {tags.map((tag, tagIndex) => (
                        <Badge key={`${item.id}-tag-${tagIndex}`} variant="secondary" className="text-xs">
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  </CardContent>
                  <CardFooter className="flex justify-between p-3 pt-0 text-xs text-muted-foreground">
                    <span>{new Date(item.timestamp).toLocaleDateString()}</span>
                    <span>{objectsCount} 个对象</span>
                  </CardFooter>
                </Card>
              </Link>
            )
          })}
        </div>
      )}
    </div>
  )
}
